<template>
  <div>
    <!-- 图片上传组件辅助-->
    <el-upload
      ref="myupload"
      class="my-input-upload"
      :action="ossObj.host ? ossObj.host : ''"
      :data="ossObj"
      :headers="header"
      :show-file-list="false"
      :on-success="uploadSuccess"
      :before-upload="beforeUpload"
      :on-change="uploadChangeImg"
      :on-error="uploadError"
    />
    <quill-editor ref="myQuillEditor" v-model="content" :options="editorOption" @change="onEditorChange($event)" />
  </div>
</template>

<script>
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // toggled buttons
  ['blockquote', 'code-block'],
  [{ header: 1 }, { header: 2 }], // custom button values
  [{ list: 'ordered' }, { list: 'bullet' }],
  [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
  [{ direction: 'rtl' }], // text direction
  [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
  [{ header: [1, 2, 3, 4, 5, 6, false] }],
  [{ color: [] }, { background: [] }], // dropdown with defaults from theme
  [{ font: [] }],
  [{ align: [] }],
  ['link', 'image'],
  ['clean']
]
export default {
  props: {
    editContent: {
      // 内容
      type: String,
      default: ''
    }
  },
  data() {
    return {
      quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
      content: null,
      editorOption: {
        placeholder: '店铺介绍不得少于10字，且不得超过2500字！',
        theme: 'snow', // or 'bubble'
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: function(value) {
                if (value) {
                  // 触发input框选择图片文件
                  document.querySelector('.my-input-upload input').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      serverUrl: '', // 这里写你要上传的图片服务器地址
      header: {
        // token: sessionStorage.token
      }, // 有的图片服务器要求请求头需要有token
      ossObj: {
        'accessid': 'LTAI4GE96UTYzhh9oqqevSfT',
			    'policy': 'eyJleHBpcmF0aW9uIjoiMjAyMC0wNi0wMVQwMjozMDoyMi4xMzJaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjAwMF0sWyJzdGFydHMtd2l0aCIsIiRrZXkiLCJ0ZW1wLyJdXX0=',
			    'signature': 'qjrVY3vW7r8eWmI77P5y0g/QLio=',
			    'dir': 'temp/',
			    'host': 'https://yitui-bucket-temp.oss-cn-shenzhen.aliyuncs.com',
			    'expire': '1590978622',
			    'callback': 'eyJjYWxsYmFja0JvZHlUeXBlIjoiYXBwbGljYXRpb24veC13d3ctZm9ybS11cmxlbmNvZGVkIiwiY2FsbGJhY2tVcmwiOiJodHRwOi8vMTEyLjc0LjEwMi4yMDI6NzA3MC9vc3NDYWxsYmFjayIsImNhbGxiYWNrQm9keSI6ImZpbGVuYW1lPSR7b2JqZWN0fSZzaW1wbGVuYW1lPSR7c2ltcGxlTmFtZX0mc2l6ZT0ke3NpemV9Jm1pbWVUeXBlPSR7bWltZVR5cGV9JmhlaWdodD0ke2ltYWdlSW5mby5oZWlnaHR9JndpZHRoPSR7aW1hZ2VJbmZvLndpZHRofSJ9'
      }
    }
  },
  watch: {
    editContent: {
      handler(newName, oldName) {
		  　　	this.content = newName
      },
      immediate: true
    }
  },
  mounted() {
    this.content = this.editContent
  },
  methods: {
    uploadSuccess() {
		 	// res为图片服务器返回的数据
		 	// 获取富文本组件实例
		 	// console.log(res);
		 	const path = this.ossObj.path

		 	const quill = this.$refs.myQuillEditor.quill
		 	// 如果上传成功
		 	this.toutiaoImage(path).then(() => {
		 		console.log('path', path)
		 	    // this.imageUrl = path;
		 		// if (res.code == 200) {
		 		// 	// 获取光标所在位置
		 		console.log(quill.getSelection())
		 			const length = quill.getSelection().index
		 		// 	// 插入图片  res.url为服务器返回的图片地址
		 			quill.insertEmbed(length, 'image', path)
		 		// 	// 调整光标到最后
		 			quill.setSelection(length + 1)
		 		// } else {
		 		// 	this.$message.error('图片插入失败');
		 		// }
		 	})

		 	// loading动画消失
		 	this.quillUpdateImg = false
		 },
    uploadChangeImg() {
      console.log('changeImg')
      this.modifyOssFn().then(res => {
			    this.$refs.myupload.submit()
      })
    },
    onEditorChange({ editor, html, text }) {
      // 内容改变事件
      console.log('---内容改变事件---')
      this.content = html
      // console.log(html);
    },
    // 富文本图片上传前
    beforeUpload(file) {
      // 显示loading动画
      console.log(this.ossObj)
      this.quillUpdateImg = true
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
			    this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    // 富文本图片上传失败
    uploadError() {
      // loading动画消失
      this.quillUpdateImg = false
      this.$message.error('图片插入失败')
    },
    editSubmit() {
      this.$emit('editSubmit', this.content)
    }
  }
}
</script>

<style>
	.my-input-upload{
		opacity: 0;
		height: 5px;
		width: 100px;
	}
.ql-editor.ql-blank,
.ql-editor {
	height: 350px;
}
</style>
